package com.shopping.service.impl;

import com.shopping.bean.Cart;
import com.shopping.bean.Product;
import com.shopping.dao.CartDao;
import com.shopping.service.ICartService;
import com.shopping.util.Page;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService implements ICartService {
    @Autowired
    CartDao cartDao;
    @Override
    public int addCart(Cart cart) {
        Cart cart_data=getCart(cart);
        if (cart_data==null){
            cart.setQuantity(1);
            return cartDao.addCart(cart);
        }else {
            cart.setQuantity(cart_data.getQuantity()+1);
            return  cartDao.editCart(cart);
        }
    }


    @Override
    public Cart editCart(Cart cart) {
        int number=cart.getQuantity();

        if(number>=99){
            cart.setQuantity(99);
            cartDao.editCart(cart);
            throw new RuntimeException("购物车数量不能大于99");
        }
        if(number<=0){
            cart.setQuantity(1);
            cartDao.editCart(cart);
            throw new RuntimeException("购物车数量不能小于1");
        }
        cartDao.editCart(cart);
        return cart;
    }
    @Override
    public int deleteCart(Cart cart) {
        return cartDao.deleteCart(cart);
    }

    @Override
    public List<Cart> getList(Page page, String text) {
        return cartDao.getList(page,text);
    }

    @Override
    public Product getProductById(int id) {
        return null;
    }


    @Override
    public int getCount(String text) {
        return cartDao.getCount(text);
    }
    @Override
    public Cart getCart(@Param("cart") Cart cart) {
        return cartDao.getCart(cart);
    }
    @Override
    public List<Cart> getCarts(int userid) {
        return cartDao.getCarts(userid);
    }
}
